from ldap3 import Server, Connection, ALL, SUBTREE
import datetime


def Adsync():
    delta = datetime.timedelta(days=2)
    today = datetime.datetime.now()
    yesterday = (today - delta).strftime('%Y%m%d160000.0Z')

    server = Server('10.30.0.46', get_info=ALL)
    conn = Connection(server, user='it-ops@wifi.lead.com', password='Qwerty.123456', auto_bind=True)

    rs = conn.search(search_base='dc=wifi,dc=lead,dc=com',
                search_filter='(&(whenCreated>={})(objectCategory=CN=Person,CN=Schema,CN=Configuration,DC=wifi,DC=lead,DC=com))'.format(
                    yesterday),
                search_scope=SUBTREE,
                attributes=['sAMAccountName', 'name', 'distinguishedName'])
    # 初始化列表
    newcomer_list = []
    for entries_obj in conn.entries:
        '''
        提取工号、姓名、部门
        '''
        # 初始化字典
        newcomer_dic = {}
        newcomer_dic['workno'] = entries_obj.sAMAccountName.value
        newcomer_dic['name'] = entries_obj.name.value
        newcomer_dic['dept'] = entries_obj.distinguishedName.value.split('OU=')[1].rstrip(',')
        newcomer_list.append(newcomer_dic)
    return newcomer_list

if __name__ == '__main__':
    print(Adsync())